<?php
namespace Admin\Controller;

use Think\Controller;

class LoginController extends Controller
{
    /**
     * 登陆首页
     */
    public function index()
    {
        $this->display();
    }

    /**
     * 登陆验证
     */
    public function login()
    {
        if (!IS_POST) {
            $this->show("非法请求");
            return;
        }
        $username = I('username', '', 'addslashes');
        $password = I('password', '', 'md5');
        $code = I('verify', '', 'strtolower');

        //验证验证码是否正确
        if (!($this->check_verify($code))) {
            $this->show('验证码错误');
            return;
        }

        $condition['username'] = $username;
        $condition['password'] = $password;

        //验证账号密码是否正确
        $user = M('admin')->where($condition)->find();

        if (!$user) {
            $this->show('账号或密码错误');
            return;
        }

        session('adminId', $user['id']);
        session('username', $user['username']);

        redirect(U('Index/index'));
    }

    public function verify()
    {
        $Verify = new \Think\Verify();
        $Verify->codeSet = '0123456789';
        $Verify->fontSize = 13;
        $Verify->length = 4;
        $Verify->entry();
    }

    protected function check_verify($code)
    {
        $verify = new \Think\Verify();
        return $verify->check($code);
    }

    /**
     * 注销退出
     */
    public function logout()
    {
        session('adminId', null);
        session('username', null);
        redirect(U('Index/index'));
    }
}